package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")
//@SuppressWarnings({"all"})
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 用于完成员工登录
     *
     * @param employee
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {

        if (employee == null || StringUtils.isBlank(employee.getUsername()) ||
                StringUtils.isBlank(employee.getPassword())) {
            return R.error("用户名或密码不能为空!");
        }
        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("用户名不存在!");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!password.equals(emp.getPassword())) {
            return R.error("用户名或密码错误!");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == null || (1 != emp.getStatus())) {
            return R.error("员工账号已禁用!");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        //以 "employeeId",String 的形式 在 Session 中存入用户 id
        request.getSession().setAttribute("employeeId", emp.getId().toString());
        emp.setPassword(null);
        return R.success(emp);
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().invalidate(); //清除 Session
        return R.success("");
    }

    /**
     * 新增员工
     *
     * @param employee
     * @param request
     * @return
     */
    @PostMapping
    public R<Object> save(@RequestBody Employee employee, HttpServletRequest request) {
        log.info("新增员工，员工信息：{}", employee.toString());
        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //获得当前登录用户的id, 设置为新建用户的 createUser updateUser
//        Long empId = Long.valueOf((String) request.getSession().getAttribute("employeeId"));
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        //调用 employeeService 存储
        boolean saveFlag = employeeService.save(employee);
        if (!saveFlag) {
            return R.error("添加员工失败");
        }
        return R.success("成功添加员工");
    }

    /**
     * 员工信息分页查询
     *
     * @param page     当前查询页码
     * @param pageSize 每页展示记录数
     * @param name     员工姓名 - 可选参数
     * @return
     */
    @GetMapping("/page")
    public R<Object> page(Integer page, Integer pageSize, String name) {
        if (page == null || pageSize == null || page <= 0) {
            return R.error("请求参数有误");
        }
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);
        //由分页构造器 创建分页对象
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        // 如果 name 不为空 ,则 根据 name 模糊查询 (条件查询)
        lqw.like(StringUtils.isNotBlank(name), Employee::getName, name);
        //添加排序条件
        lqw.orderByAsc(Employee::getId);
        //执行查询
        employeeService.page(pageInfo, lqw);
        HashMap<String, Object> map = new HashMap<>();
        map.put("records", pageInfo.getRecords());
        map.put("total", pageInfo.getTotal());
        return R.success(map);
    }

    /**
     * 修改员工状态与修改员工信息使用同一控制器方法
     * 修改的时, 只修改员工属性有值的字段
     *
     * @param employee
     * @param request
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpServletRequest request) {
        log.info(employee.toString());
        if (employee.getId() == null || employee.getStatus() == null) {
            return R.error("请求参数有误");
        }
//        Long empId = Long.valueOf((String) request.getSession().getAttribute("employeeId"));
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empId);
        boolean updateFlag = employeeService.updateById(employee);
        if (!updateFlag) {
            return R.error("员工信息修改失败");
        }
        return R.success("员工信息修改成功");
    }

    @GetMapping("/{id}")
    public R<Object> findById(@PathVariable Long id) {
        if (id == null || id <= 0) {
            return R.error("请求参数有误");
        }
        Employee employee = employeeService.getById(id);
        if (employee == null) {
            return R.error("查询员工信息失败");
        }
        employee.setPassword(null);
        return R.success(employee);
    }


    //导出员工表 文件下载 excel
    //不能用 axios 请求
    @GetMapping("/export")
    public void exportEmployee(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel; charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=employee.xlsx");
            List<Employee> list = employeeService.list();
            EasyExcel.write(response.getOutputStream(), Employee.class)
                    .registerConverter(new LongStringConverter())
                    .sheet("test")
                    .doWrite(list);
        } catch (Exception e) {
            log.error("下载报表异常：{}", e.getMessage());
            throw new RuntimeException("下载报表异常");
        }
    }

}
